/*************************************************************************
	> File Name: Log.hpp
	> Author: H.M. Lau
	> Mail: hm.lau@outlook.com
	> Created Time: 2023/10/15 14:37
 ************************************************************************/

#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <cstdio>
#include <cerrno>
#include <cstdarg>
#include <ctime>

const int STD_SIZE = 64;
const int TIME_SIZE = 32;
const int LOG_SIZE = 1024;

const std::string filename = "Calc.log";

enum Level { DEBUG, NORMAL, WARNING, ERROR, FATAL };

std::string gLevelMap[] = {
    "DEBUG",
    "NORMAL",
    "WARNING",
    "ERROR",
    "FATAL"   
};

void logMessage(const int level, const char* format, ...)
{
#ifndef DEBUG_SHOW
    if (level == DEBUG) {
        return ;
    }
#endif
    char stdBuffer[STD_SIZE];
    char timeBuffer[TIME_SIZE];
    char logBuffer[LOG_SIZE];
    time_t t = time(nullptr);
    struct tm* timeinfo = localtime(&t);
    strftime(timeBuffer, sizeof timeBuffer, "%Y-%m-%d %H:%M:%S", timeinfo);
    snprintf(stdBuffer, sizeof stdBuffer, "[%s][%s]", gLevelMap[level].c_str(), timeBuffer);
    va_list args;
    va_start(args, format);
    vsnprintf(logBuffer, sizeof logBuffer, format, args);
    va_end(args);
#ifdef LOG_FILE
    FILE* fp = fopen(filename.c_str(), "a");
    if (!fp) {
        printf("fopen error, %d:%s\n", errno, strerror(errno));
        exit(1);
    }
    fprintf(fp, "%s%s\n", stdBuffer, logBuffer);
    fclose(fp);
#else
    printf("%s%s\n", stdBuffer, logBuffer);
#endif
}
